import http from '@ohos.net.http'

import Logger from '../model/Logger'

const TAG = '[aaaaa]'

export class HuaweiCloudApi {
    IAMEndpoint: string
    IOTDAEndpoint: string
    IAMUserName: string
    IAMPassword: string
    IAMDoaminId: string
    region: string
    X_Auth_Token: Object
    project_id: string
    product_id: string
    device_id: string

    requestData: http.HttpResponse = undefined

    constructor() {}

    async request(uri: string, op: Object) {
        let httpRequest = http.createHttp()
        Logger.info(TAG, `createHttp uri = ${uri}`)
        try {
            let result = await httpRequest.request(uri, op) //JS API 网络数据请求
            Logger.info(TAG, `HttpResponse's result is ${JSON.stringify(result.result)}`)
            Logger.info(TAG, `responseCode is ${result.responseCode} header is ${JSON.stringify(result.header)}
        cookies is ${JSON.stringify(result.cookies)}}`)
            return result
        } catch (err) {
            Logger.info(TAG, `This err is ${JSON.stringify(err)}`)
            httpRequest.destroy()
            return err
        }
    }

    /* 官方文档：https://support.huaweicloud.com/api-iam/iam_30_0001.html*/
    async getIAMUserToken(){
        let PostHeader = {
            'Content-Type': 'application/json'
        }
        let PostBody = {
            "auth": {
                "identity": {
                    "methods": [
                        "password"
                    ],
                    "password": {
                        "user": {
                            "name": this.IAMUserName,
                            "password": this.IAMPassword,
                            "domain": {
                                "name": this.IAMDoaminId
                            }
                        }
                    }
                },
                "scope": {
                    "project": {
                        "name": this.region
                    }
                }
            }
        }
        let requestData = await this.request('https://iam.cn-north-4.myhuaweicloud.com/v3/auth/tokens', { //发起网络数据请求,url/请求头
            method: http.RequestMethod.POST,
            extraData: PostBody,  // 请求体
            header: PostHeader,
            readTimeout: 5000,
            connectTimeout: 5000,
        })
        Logger.info(TAG, `getIAMUserToken header is ${JSON.stringify(requestData)}`)//响应头.Object类型
        Logger.info(TAG, `getIAMUserToken header is ${JSON.stringify(requestData.header)}`)//响应头.Object类型
        Logger.info(TAG, `getIAMUserToken result is ${JSON.stringify(requestData.result)}`)//相应体.string类型
        return requestData.header['X-Subject-Token']
    }

    /* 官方文档：https://support.huaweicloud.com/api-iothub/iot_06_v5_0079.html*/
    async showDeviceShadow(){
        let PostHeader = {
            'Content-Type': 'application/json',
            'X-Auth-Token': this.X_Auth_Token
            //'X-Auth-Token': "MIIUTwYJKoZIhvcNAQcCoIIUQDCCFDwCAQExDTALBglghkgBZQMEAgEwghJhBgkqhkiG9w0BBwGgghJSBIISTnsidG9rZW4iOnsiZXhwaXJlc19hdCI6IjIwMjItMDgtMjRUMjI6NTQ6MTUuMTUwMDAwWiIsIm1ldGhvZHMiOlsicGFzc3dvcmQiXSwiY2F0YWxvZyI6W10sInJvbGVzIjpbeyJuYW1lIjoidGVfYWRtaW4iLCJpZCI6IjAifSx7Im5hbWUiOiJ0ZV9hZ2VuY3kiLCJpZCI6IjAifSx7Im5hbWUiOiJvcF9nYXRlZF9lY3Nfc3BvdF9pbnN0YW5jZSIsImlkIjoiMCJ9LHsibmFtZSI6Im9wX2dhdGVkX2l2YXNfdmNyX3ZjYSIsImlkIjoiMCJ9LHsibmFtZSI6Im9wX2dhdGVkX2FfY24tc291dGgtNGMiLCJpZCI6IjAifSx7Im5hbWUiOiJvcF9nYXRlZF9lY3Nfa2FlMSIsImlkIjoiMCJ9LHsibmFtZSI6Im9wX2dhdGVkX2R3c19wb2MiLCJpZCI6IjAifSx7Im5hbWUiOiJvcF9nYXRlZF9jYnJfZmlsZSIsImlkIjoiMCJ9LHsibmFtZSI6Im9wX2dhdGVkX2Vjc19rYzFfdXNlcl9kZWZpbmVkIiwiaWQiOiIwIn0seyJuYW1lIjoib3BfZ2F0ZWRfbWVldGluZ19lbmRwb2ludF9idXkiLCJpZCI6IjAifSx7Im5hbWUiOiJvcF9nYXRlZF9tYXBfbmxwIiwiaWQiOiIwIn0seyJuYW1lIjoib3BfZ2F0ZWRfZWdfY24iLCJpZCI6IjAifSx7Im5hbWUiOiJvcF9nYXRlZF9zYWRfYmV0YSIsImlkIjoiMCJ9LHsibmFtZSI6Im9wX2dhdGVkX3NlcnZpY2VzdGFnZV9tZ3JfZHRtX2VuIiwiaWQiOi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E4NzAxOGI2NjAwZjIyNzBmNGNjMDBjYzkzNjY5NDAifSwibmFtZSI6IkJyaWdodF9NTCIsInBhc3N3b3JkX2V4cGlyZXNfYXQiOiIiLCJpZCI6IjBhODcwMThjNTQ4MGYyMmMxZjE2YzAwYzk5Njk0NzMzIn19fTGCAcEwggG9AgEBMIGXMIGJMQswCQYDVQQGEwJDTjESMBAGA1UECAwJR3VhbmdEb25nMREwDwYDVQQHDAhTaGVuWmhlbjEuMCwGA1UECgwlSHVhd2VpIFNvZnR3YXJlIFRlY2hub2xvZ2llcyBDby4sIEx0ZDEOMAwGA1UECwwFQ2xvdWQxEzARBgNVBAMMCmNhLmlhbS5wa2kCCQDcsytdEGFqEDALBglghkgBZQMEAgEwDQYJKoZIhvcNAQEBBQAEggEALD7mdRhuVjNpUFRGlw1H8Tjx8cjKIBJGhFcxOxB3oQlwRuiO9jXI8E3cLMl8IsgueNPrp4Z7CfxaTBAN2CJ42P7lyW1Onq-yrW8BD-GHhmHHt0LA4oY63qze1i6bgVBavLC+p16HnaszDGrqgWb9rmpTD1WLFRGw+yqHcBFxxUoJBpQpJmFR96-Q2Bt8yooNPTF-D6v3i3jHhFS5XkIhTLxxhqBRCyFBfY4929md+TwOFQ2IkHOwi0K2LSC08YB1JGYciSS8lLnKTuw7mgA3W+BMZIC0Z-pck1FET6IJtmgP9xIiq+E5hW6NPo5msZSB+Y1+Zphu19re+9k6bltb0g=="
        }
        let PostBody = {}



        // 每一个httpRequest对应一个http请求任务，不可复用
        let httpRequest = http.createHttp();
        // 用于订阅http响应头，此接口会比request请求先返回。可以根据业务需要订阅此消息
        // 从API 8开始，使用on('headersReceive', Callback)替代on('headerReceive', AsyncCallback)。 8+
        httpRequest.on('headersReceive', (header) => {
            console.info('header: ' + JSON.stringify(header));
        });

        httpRequest.request("https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/'+this.project_id+'/devices/'+this.device_id+'/shadow",
            {
                method: http.RequestMethod.GET, // 可选，默认为http.RequestMethod.GET
                // 开发者根据自身业务需要添加header字段
                header: {
                    'Content-Type': 'application/json',
                    'X-Auth-Token': this.X_Auth_Token
                },
                // 当使用POST请求时此字段用于传递内容
                extraData: {
                    "data": "data to send",
                },
                connectTimeout: 60000, // 可选，默认为60s
                readTimeout: 60000, // 可选，默认为60s
            },(err, data) => {
            if (!err) {
                console.info('Result:' + data.result);
                console.info('code:' + data.responseCode);
                console.info('header:' + JSON.stringify(data.header));
                console.info('cookies:' + data.cookies); // 8+
            } else {
                console.info('error:' + JSON.stringify(err));
            }
        });



        let requestData = await this.request('https://iotda.cn-north-4.myhuaweicloud.com/v5/iot/'+this.project_id+'/devices/'+this.device_id+'/shadow', { //发起网络数据请求,url/请求头
            method: http.RequestMethod.GET,
            extraData: PostBody,  // 请求体
            header: PostHeader,
            readTimeout: 5000,
            connectTimeout: 5000,
        })
        Logger.info(TAG, `showDeviceShadow header is ${JSON.stringify(requestData.header)}`)//响应头.Object类型
        Logger.info(TAG, `showDeviceShadow result is ${JSON.stringify(requestData.result)}`)//相应体.string类型
//        return JSON.stringify(JSON.parse(requestData.result).shadow[0].reported.properties.InVoltage)
        return JSON.parse(requestData.result).shadow[0].reported.properties
    }

}

export default new HuaweiCloudApi()